import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
import csv
import execjs
import requests


class GJYB:
    def __init__(self):
        self.url = "https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/CommQuery/queryFixedHospital"
        self.headers = {
            "accept": "application/json",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "channel": "web",
            "connection": "keep-alive",
            "content-length": "0",
            "content-type": "application/json",
            "contenttype": "application/x-www-form-urlencoded",
            "cookie": "amap_local=370000; acw_tc=276aede217464154385431828e5c465eb1dacb5a4e012c94a46d416eafbd81; yb_header_active=-1",
            "host": "fuwu.nhsa.gov.cn",
            "origin": "https://fuwu.nhsa.gov.cn",
            "pragma": "no-cache",
            "referer": "https://fuwu.nhsa.gov.cn/nationalHallSt/",
            "sec-ch-ua": "\"Chromium\";v=\"136\", \"Microsoft Edge\";v=\"136\", \"Not.A/Brand\";v=\"99\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0",
            "x-tif-nonce": "",
            "x-tif-paasid": "undefined",
            "x-tif-signature": "",
            "x-tif-timestamp": 1746415471,
            "x-tingyun": ""
        }
        self.param = {
            "addr": "",
            "regnCode": "370000",
            "medinsName": "",
            "medinsLvCode": "",
            "medinsTypeCode": "",
            "outMedOpenFlag": "",
            "pageNum": 1,
            "pageSize": 10,
            "queryDataSource": "es"
        }
        self.data = None

    # 获取请求头加密字段
    def get_header(self):
        with open('国家医保header.js', 'r', encoding='utf-8') as f:
            js = f.read()
        js = execjs.compile(js)
        code = js.call('get_header')
        self.headers['x-tif-nonce'] = code.get('nonce')
        self.headers['x-tif-signature'] = code.get('signature')
        self.headers['x-tif-timestamp'] = str(code.get('timestamp'))
        self.headers['x-tingyun'] = code.get('Tingyun')

    def get_param(self, page):
        self.param['pageNum'] = page
        with open('国家医保data.js', 'r', encoding='utf-8') as f:
            js = f.read()
        js = execjs.compile(js)
        self.data = js.call('get_data', self.param)

    def get_data(self, page):
        try:
            self.get_header()
            self.get_param(page)
            response = requests.post(url=self.url, headers=self.headers, json=self.data)
            return response.json()
        except Exception as e:
            print('数据获取失败!!!', e)

    def get_res(self, response):
        with open('国家医保res.js', 'r', encoding='utf-8') as f:
            js = f.read()
        js = execjs.compile(js)
        code = js.call('get_res', response)['list']
        self.parse(code)

    def parse(self, data):
        for info in data:
            item = {}
            item['名称'] = info['medinsName']
            item['类型'] = info['medinsTypeName']
            item['等级'] = info['medinsLvName']
            item['地址'] = info['addr']
            self.save_data(item)

    def save_data(self, item):
        writer.writerow(item)

    def main(self):
        for page in range(1, 6):
            response = self.get_data(page)
            self.get_res(response)


if __name__ == '__main__':
    fp = open('医疗机构名称.csv', 'w', encoding='utf-8', newline='')
    filename = ['名称', '类型', '等级', '地址']
    writer = csv.DictWriter(fp, fieldnames=filename)
    writer.writeheader()
    GJYB().main()
